package cn.meizhu.org.controller;

import cn.meizhu.org.domain.Department;
import cn.meizhu.org.query.DepartmentQuery;
import cn.meizhu.org.service.IDepartmentService;
import cn.meizhu.util.AjaxResult;
import cn.meizhu.util.QueryResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.util.List;
@RequestMapping("/department")
@RestController
//@CrossOrigin
@Api(tags = "部门接口")
public class DepartmentController {
    @Autowired
    private IDepartmentService departmentService;

    @PutMapping
    @ApiOperation(value = "部门添加或者修改", notes = "有id就是修改，没有id就是新增")
    public AjaxResult addAndUpdDepartment(@RequestBody Department department){
        try {
            if (department.getId() == null){
                departmentService.save(department);
            }else {
                departmentService.update(department);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage(e.getMessage());
        }
    }


    @DeleteMapping("/{id}")
    @ApiOperation(value = "这是部门删除")
    public AjaxResult delDepartmentById(@PathVariable("id") Long id){
        try {
            departmentService.delete(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage(e.getMessage());
        }
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "根据id查询部门中指定数据")
    public Department findDepartmentById(@PathVariable("id") Long id){
        return departmentService.findById(id);
    }

    @GetMapping
    @ApiOperation(value = "查询部门全部数据")
    public List<Department> findDepartments(){
        return departmentService.findAll();
    }


   @PostMapping
    public QueryResult<Department> queryPage(@RequestBody DepartmentQuery departmentQuery){
        return departmentService.queryPage(departmentQuery);
    }

    /**
     * 批量删除
     * @return
     */
    @PatchMapping
    public AjaxResult patchDelDepartmentByIds(@RequestBody Long[] ids){
        try {
            departmentService.patchDelDepartmentByIds(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return  AjaxResult.me().setMessage(e.getMessage());
        }
    }

    @GetMapping("/deptTree")
    public List<Department> loadDeptTree(){
        return departmentService.loadDeptTree();
    }
}
